/**
 * 微信开放数据域
 * 使用 Canvas2DAPI 在 SharedCanvas 渲染一个排行榜，
 * 并在主域中渲染此 SharedCanvas
 */







/**
 * 资源加载组，将所需资源地址以及引用名进行注册
 * 之后可通过assets.引用名方式进行获取
 */
const assetsUrl = {
  num_0:"resource/assets/worldRank/0.png",
  num_1:"resource/assets/worldRank/1.png",
  num_2:"resource/assets/worldRank/2.png",
  num_3:"resource/assets/worldRank/3.png",
  num_4:"resource/assets/worldRank/4.png",
  num_5:"resource/assets/worldRank/5.png",
  num_6:"resource/assets/worldRank/6.png",
  num_7:"resource/assets/worldRank/7.png",
  num_8:"resource/assets/worldRank/8.png",
  num_9:"resource/assets/worldRank/9.png",

  rank_frame: "resource/assets/worldRank/rank_frame.png",
  rank_line:"resource/assets/worldRank/rank_line.png",
  rank_line_2:"resource/assets/worldRank/rank_line_2.png",
  rank_index_1: "resource/assets/worldRank/rank_1.png",
  rank_index_2: "resource/assets/worldRank/rank_2.png",
  rank_index_3: "resource/assets/worldRank/rank_3.png"
};

/**
 * 资源加载组，将所需资源地址以及引用名进行注册
 * 之后可通过assets.引用名方式进行获取
 */
let assets = {};

let avatarUrlList = {

};

let myNickName = '';
let myOpenId = '';
let assetsAvatarUrl = {};
/**
 * canvas 大小
 * 这里暂时写死
 * 需要从主域传入
 */
let canvasWidth;
let canvasHeight;

let startIndex = 0;

//获取canvas渲染上下文
const context = sharedCanvas.getContext("2d");
context.globalCompositeOperation = "source-over";

let GroupType = 1;


/**
 * 所有头像数据
 * 包括姓名，头像图片，得分
 * 排位序号i会根据parge*perPageNum+i+1进行计算
 */
let totalGroup = [
];

/**
 * 创建排行榜
 */
function drawRankPanel() {
  const startID = perPageMaxNum * page;
  if(GroupType==1)
  {
    currentGroup = totalGroup.slice(startID, startID + perPageMaxNum);
  }
  else
    currentGroup = getRankListByMyIndex();
  //创建头像Bar
  drawRankByGroup(currentGroup);
  if(GroupType == 1)
  {
    createMyScene();
  }
}

/**
 * 获取本人前后的排行榜数据
 */
function getRankListByMyIndex()
{
  let list = [];
  if(myRank == 1)
  {
    for(let i=0;i<3;i++)
    {
      if(totalGroup[i])
      {
        let data = totalGroup[i];
        data['rank'] = i;
        list.push(data);
      }
    }
  }
  else
  {
    for(let i=myRank-2;i<myRank+1;i++)
    {
      if(totalGroup[i])
      {
        let data = totalGroup[i];
        data['rank'] = i;
        list.push(data);
      }
    }
  }
  return list;
}

/**
 * 根据屏幕大小初始化所有绘制数据
 */
function init() {
  //排行榜绘制数据初始化,可以在此处进行修改

  //根据游戏实际分辨率进行适配宽高比
  let scaleX = (stageWidth/720);
  let scaleY = (stageHeight/1280);

  //游戏内部排行榜容器的宽高
  let gameListWidth = 548;
  let gameListHeight = 360;

  //游戏内部排行榜元素的宽高
  let gameBarWidth = 548;
  let gameBarHeight = 120;
  if(GroupType == 1)
  {
    //普通好友排行榜
    gameListWidth = 496;
    gameListHeight = 717;

    gameBarWidth = 496;
    gameBarHeight = 107;
  }
  else
  {
    gameListWidth = 548;
    gameListHeight = 360;
  
    //游戏内部排行榜元素的宽高
    gameBarWidth = 548;
    gameBarHeight = 110;
  }

  rankWidth = gameListWidth * scaleX;//stageWidth * 4 / 5;
  rankHeight = gameListHeight * scaleY;//stageHeight * 4 / 5;
  barWidth = gameBarWidth;//rankWidth * 4 / 3.85;
  barHeight = gameBarHeight;//rankHeight / 12.5;

  offsetX_rankToBorder = (stageWidth - rankWidth) / 2;
  offsetY_rankToBorder = (stageHeight - rankHeight) / 2;
  preOffsetY = 0;

  let data = wx.getSystemInfoSync();
  canvasWidth = data.windowWidth;
  canvasHeight = data.windowHeight;

  startX = 0;
  startY = 0;
  avatarSize = 76;
  intervalX = 40;
}

//获取字符串长度(英文占1个字符，中文汉字占2个字符)
function strlen(str) {
  var len = 0;
  for (var i = 0; i < str.length; i++) {
    var c = str.charCodeAt(i);
    //单字节加1   
    if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
      len++;
    }
    else {
      len += 2;
    }
  }
  return len;
}

function getMyUserInfo() {
  wx.getUserInfo({
    openIdList: ['selfOpenId'],
    success: res => {
      var userInfo = res.data
      var nickName = userInfo[0].nickName
      var avatarUrl = userInfo[0].avatarUrl
      var gender = userInfo[0].gender //性别 0：未知、1：男、2：女
      var province = userInfo[0].province
      var city = userInfo[0].city
      var country = userInfo[0].country
      var openid = userInfo[0].openId
      myNickName = nickName;
      avatarUrlList[myOpenId] = avatarUrl;

      preloadAvatarUrl();
    }
  })
}

function preloadAvatarUrl() {
  let preloaded = 0;
  let count = 0;
  for (let asset in avatarUrlList) {
    if(assetsAvatarUrl[asset])continue;
    count++;
    const img = wx.createImage();
    img.onload = () => {
      preloaded++;
      if (preloaded == count) {
        // console.log("头像加载完成");
        hasLoadRes = true;
      }
    }
    // console.log("src:" + avatarUrlList[asset] + " asset:" + asset);
    img.src = avatarUrlList[asset];
    assetsAvatarUrl[asset] = img;
  }
}

/**
 * 根据当前绘制组绘制排行榜
 */
function drawRankByGroup(currentGroup) {
  for (let i = 0; i < currentGroup.length; i++) {
    const data = currentGroup[i];
    if(GroupType == 1)
      drawByData1(data, i);
    else
      drawByData(data, i);
  }
}

let myCurrentScore = 0;
let myRank = 0;
let curDataType = 'score';
/**
 * 获取玩过的好友数据
 */
function getFriendCloudStorage(key){
  curDataType = key;
  wx.getFriendCloudStorage({
    keyList:[key],
    success:(res)=>{
      totalGroup = res.data;
      if (totalGroup == null || totalGroup.length == 0) {
        return;
      }
      if(curDataType != 'score')
      {
         filterLastWeekData(totalGroup);
      }
      rankSort(totalGroup);
      page = 0;
      startIndex = 0;
      renderDirty = true;
      if (totalGroup.length >= 1) {
        for (let i = 0; i < totalGroup.length; i++) {
          let openId = totalGroup[i].openid;
          if (totalGroup[i].openid == myOpenId) {
            let kvDataList = totalGroup[i].KVDataList;
            let kvDataScore_1 = kvDataList[0];
            let score = kvDataScore_1.value;
            myCurrentScore = getFriendDataScore(totalGroup[i]);
            myRank = i + 1;
            myNickName = totalGroup[i].nickname;
            // myOpenId = openId;
            // console.log("我的排名:" + myRank + " 得分:" + myCurrentScore);           
          }
          // console.log("openId:" + openId + " nickname:" + totalGroup[i].nickname);
          avatarUrlList[openId] = totalGroup[i].avatarUrl;
        }
      }
      
      preloadAvatarUrl();

      if (!hasCreateScene) {
        //创建并初始化
        hasCreateScene = createScene(); 
      }
      requestAnimationFrameID = requestAnimationFrame(loop);
    }
  })
}

/**
 * 
 * 预加载一遍头像
 */
function getFriendHeadIcon()
{
  wx.getFriendCloudStorage({
    keyList:['score'],
    success:(res)=>{
      let userList = [];
      userList = res.data;
      // rankSort(userList);
      totalGroup = userList;
      if (userList.length >= 1) {
        for (let i = 0; i < userList.length; i++) {
          let openId = userList[i].openid;
          // console.log("openId:" + openId + " nickname:" + totalGroup[i].nickname);
          avatarUrlList[openId] = userList[i].avatarUrl;
        }
      }
      preloadAvatarUrl();
    }
  })
}

/**
 * 获取好友排行榜数据中的积分
 */
function getFriendDataScore(v){
  let kv_list = v['KVDataList'][0];
  if(kv_list && kv_list['value'] != null){
    let data = JSON.parse(kv_list['value']);
    return data['wxgame']['score'];
  }
  return 0;
}

/**
 * 获取好友排行榜中的上传时间
 */
function getFriendDataTime(v){
  let kv_list = v['KVDataList'][0];
  if(kv_list && kv_list['value'] != null){
    let data = JSON.parse(kv_list['value']);
    return data['wxgame']['update_time'];
  }
  return 0;
}

//过滤上一周的数据
function filterLastWeekData(_userDataList) {
  // console.log("len:" + _userDataList.length)
  //先过滤掉没成绩或者没上传时间的数据
  for (let i = 0; i < _userDataList.length; i++) {
    let kvDataListTime_1 = _userDataList[i].KVDataList;
    if (kvDataListTime_1[0] == null) {
      _userDataList.splice(i, 1);
      i -= 1;
    }
  }
  // console.log("tempLen:" + tempLen)
  for (let i = 0; i < _userDataList.length; i++) {
    // console.log("过滤后tempLen:" + tempLen)
    // console.log(_userDataList)
    if (_userDataList[i]) {
      // console.log("_userDataList i:" + i)
      let myTime = getFriendDataTime(_userDataList[i]);

      if (myTime) {
        // if (isSameDay(myTime) == false) {
        //   _userDataList.splice(i, 1);
        // }
        if (isSameWeek(myTime)) {
        } else {
          _userDataList.splice(i, 1);
          i -= 1;
        }
      }
    }
  }
}

//判断是否是同一天
function isSameDay(str) {
  console.log("str:" + str + " date:" + new Date(parseInt(str)).toDateString())
  if (new Date(parseInt(str)).toDateString() === new Date().toDateString()) {
    //当天
    // console.log("当天");
    return true;
  } else {
    //不是同一天
    // console.log("不是同一天");
    return false;
  }
}

//判断是否是同一周
function isSameWeek(oldTime) {
  oldTime = parseInt(oldTime);
  var newTime = Math.floor(new Date().getTime()/1000);

  let oneDayTime = 60 * 60 * 24;
  // console.log("now:" + newTime + " old:" + oldTime + " off:" + (newTime - oldTime) + " one:" + (oneDayTime * 7))
  let oldDate = new Date(oldTime * 1000);
  let newDate = new Date(newTime * 1000);

  let oldDay = oldDate.getDay();
  let newDay = newDate.getDay();

  if (newDay == 0) {
    newDay = 7;
  }
  if (oldDay == 0) {
    oldDay = 7;
  }
  
  let isSame = false;
  if (oldDay < newDay) {
    if ((newTime - oldTime) < oneDayTime * 7) {  // 时间相差小于7
      isSame = true;
    }
  } 
  else if (oldDay == newDay) {
    if ((newTime - oldTime) < oneDayTime) {
      isSame = true;
    } 
  }
  return isSame;
}

/**
	 * 上传用户分数到微信后台
	 */
function uploadUserScore(score, type) {
  	let value = JSON.stringify({
				wxgame:{
					score:score,
					update_time:Math.floor(new Date().getTime()/1000)
				},
				cost_ms:1000
			});

      window.platform.setUserDataToCould([{
        key:type,
        value:value
		}]);
}

/**
 * 按照积分排序
 */
function rankSort(list){
  list.sort((a,b)=>{
    let s1 = getFriendDataScore(a);
    let s2 = getFriendDataScore(b);
    return s2 - s1;
  });
}

//缩短昵称,超过12个字符，都缩短
function getNameSlice(nameStr) {
  let tempName = nameStr;
  if (strlen(nameStr) > 12) {
    tempName = nameStr.substring(0, 6) + "...";
  }
  return tempName;
}

/**
 * 世界排行榜展示
 */
function drawByData1(data, i) {
  let x = startX;
  let index = i + 1 + startIndex;
  // let score = data.scroes;
  let headframe = assets.rank_frame;
  let tempstartY = startY + (barHeight - assets.num_0.height) / 2;
  let headY = startY + (barHeight - headframe.height) / 2;

  //绘制序号
  if (index <= 3) {
    let deltY = (barHeight - assets['rank_index_'+index].height) >> 1;
    //前三名
    context_drawImage(assets["rank_index_"+index], x + 14, deltY + i * (preOffsetY + barHeight), 80, 76);
  } else {
    let hundredNum = Math.floor(index / 100);
    let decadeNum = Math.floor((index % 100) / 10);
    let unitNum = Math.floor((index % 100) % 10);
    let delx = 40;
    let deltY = (barHeight - assets.num_0.height) >> 1;
    if(hundredNum > 0)
    {
      delx = 14;
      context_drawImage(assets['num_'+hundredNum], x + delx, deltY + i * (preOffsetY + barHeight), 28, 36);
      context_drawImage(assets['num_'+decadeNum], x + delx + 14, deltY + i * (preOffsetY + barHeight), 28, 36);
      context_drawImage(assets['num_'+unitNum], x + delx + 28, deltY + i * (preOffsetY + barHeight), 28, 36);
    }
    else if(decadeNum > 0)
    {
      delx = 26;
      context_drawImage(assets['num_'+decadeNum], x + delx, deltY + i * (preOffsetY + barHeight), 28, 36);
      context_drawImage(assets['num_'+unitNum], x + delx + 20, deltY + i * (preOffsetY + barHeight), 28, 36);
    }
    else
    {
      context_drawImage(assets['num_'+unitNum], x + delx, deltY + i * (preOffsetY + barHeight), 28, 36);
    }
  }

  //绘制头像
  context_drawImage(headframe, x + 131, headY + i * (preOffsetY + barHeight), avatarSize+10, avatarSize+10);
  let avatarurl_x = x + 136;
  let avatarurl_y = headY + i * (preOffsetY + barHeight) + 6;
  let r = avatarSize/2;
  context.save();

  context.beginPath();
  context.arc(avatarurl_x+r, avatarurl_y+r, r, Math.PI * 2, false);
  context.clip();

  context_drawImage(assetsAvatarUrl[data.openid], avatarurl_x, avatarurl_y, avatarSize, avatarSize);
  // context_drawImage(assetsAvatarUrl[myOpenId], avatarurl_x, avatarurl_y, avatarSize, avatarSize);

  context.restore();

  //绘制名字
  context.fillStyle = '#024C90';
  context.font = '24px Arial';
  context.fillText(getNameSlice(data.nickname + ""), x + 240, tempstartY + 24 + i * (preOffsetY + barHeight));
  
  //绘制分数
  let score = getFriendDataScore(data);
  // context.fillText(getFriendDataScore(data), x + 450, tempstartY + i * (preOffsetY + barHeight));
  if(curDataType == 'score')
    context.fillText('第'+score+'关', x + 388, tempstartY + 24 + i * (preOffsetY + barHeight));
  else
    context.fillText(score+'分', x + 388, tempstartY + 24 + i * (preOffsetY + barHeight));

  //绘制线
  if(index % 5 != 0)
  context_drawImage(assets['rank_line_2'], 17, i * (preOffsetY + barHeight) + barHeight, 462, 0);
}

/**
 * 根据绘制信息以及当前i绘制元素
 */
function drawByData(data, i) {
  let x = startX;
  let index;
  if(data.rank)
    index = data.rank + 1 + startIndex;
  else
    index = i + 1 + startIndex;
  // let score = data.scroes;
  let headframe = assets.rank_frame;
  let tempstartY = startY + (barHeight - assets.num_0.height) / 2;
  let headY = startY + (barHeight - headframe.height) / 2;

  //绘制序号
  if (index <= 3) {
    let deltY = (barHeight - assets.rank_index_1.height) >> 1
    //前三名
    context_drawImage(assets["rank_index_"+index], x + 16, deltY + i * (preOffsetY + barHeight), 80, 76);
  } else {
    let hundredNum = Math.floor(index / 100);
    let decadeNum = Math.floor((index % 100) / 10);
    let unitNum = Math.floor((index % 100) % 10);
    let delx = 40;
    let deltY = (barHeight - assets.num_0.height) >> 1
    if(hundredNum > 0)
    {
      delx = 14;
      context_drawImage(assets['num_'+hundredNum], x + delx, deltY + i * (preOffsetY + barHeight), 28, 36);
      context_drawImage(assets['num_'+decadeNum], x + delx + 14, deltY + i * (preOffsetY + barHeight), 28, 36);
      context_drawImage(assets['num_'+unitNum], x + delx + 28, deltY + i * (preOffsetY + barHeight), 28, 36);
    }
    else if(decadeNum > 0)
    {
      delx = 26;
      context_drawImage(assets['num_'+decadeNum], x + delx, deltY + i * (preOffsetY + barHeight), 28, 36);
      context_drawImage(assets['num_'+unitNum], x + delx + 20, deltY + i * (preOffsetY + barHeight), 28, 36);
    }
    else
    {
      context_drawImage(assets['num_'+unitNum], x + delx, deltY + i * (preOffsetY + barHeight), 28, 36);
    }
  }

  //绘制头像
  context_drawImage(headframe, x + 135, headY + i * (preOffsetY + barHeight), avatarSize+10, avatarSize+10);
  let avatarurl_x = x + 140;
  let avatarurl_y = headY + i * (preOffsetY + barHeight) + 4;
  let r = avatarSize/2;
  context.save();

  context.beginPath();
  context.arc(avatarurl_x+r, avatarurl_y+r, r, Math.PI * 2, false);
  context.clip();
  context_drawImage(assetsAvatarUrl[data.openid], avatarurl_x, avatarurl_y, avatarSize, avatarSize);
  // context_drawImage(assetsAvatarUrl[myOpenId], avatarurl_x, avatarurl_y, avatarSize, avatarSize);

  context.restore();

  //绘制名字
  context.fillStyle = '#024C90';
  context.font = '24px Arial';
  context.fillText(getNameSlice(data.nickname + ""), x + 250, tempstartY + 24 + i * (preOffsetY + barHeight));
  
  //绘制分数
  let score = getFriendDataScore(data);
  // context.fillText(getFriendDataScore(data), x + 450, tempstartY + i * (preOffsetY + barHeight));
  context.fillText('第'+score+'关', x + 388, tempstartY + 24 + i * (preOffsetY + barHeight));

  //绘制线
  if(i < 2)
  context_drawImage(assets['rank_line'], 9, i * (preOffsetY + barHeight - 6) + barHeight, 530, 0);
}

//绘制自己的排行
function createMyScene() {
  let x = startX;
  let index = myRank;
  // let score = data.scroes;
  let headframe = assets.rank_frame;
  let startY = 614 - 107;
  let tempstartY = startY + (barHeight - assets.num_0.height) / 2;
  let headY = startY + (barHeight - headframe.height) / 2;

  //绘制序号
  if (index <= 3) {
    let deltY = startY + (barHeight - assets.rank_index_1.height) / 2
    //前三名
    context_drawImage(assets["rank_index_"+index], x + 14, deltY + (preOffsetY + barHeight), 80, 76);
  } else {
    let hundredNum = Math.floor(index / 100);
    let decadeNum = Math.floor((index % 100) / 10);
    let unitNum = Math.floor((index % 100) % 10);
    let delx = 40;
    let deltY = startY + (barHeight - assets.num_0.height) / 2;
    if(hundredNum > 0)
    {
      delx = 14;
      context_drawImage(assets['num_'+hundredNum], x + delx, deltY + (preOffsetY + barHeight), 28, 36);
      context_drawImage(assets['num_'+decadeNum], x + delx + 14, deltY + (preOffsetY + barHeight), 28, 36);
      context_drawImage(assets['num_'+unitNum], x + delx + 28, deltY + (preOffsetY + barHeight), 28, 36);
    }
    else if(decadeNum > 0)
    {
      delx = 26;
      context_drawImage(assets['num_'+decadeNum], x + delx, deltY + (preOffsetY + barHeight), 28, 36);
      context_drawImage(assets['num_'+unitNum], x + delx + 20, deltY + (preOffsetY + barHeight), 28, 36);
    }
    else
    {
      context_drawImage(assets['num_'+unitNum], x + delx, deltY + (preOffsetY + barHeight), 28, 36);
    }
  }

  //绘制头像
  context_drawImage(headframe, x + 131, headY + (preOffsetY + barHeight), avatarSize+10, avatarSize+10);
  let avatarurl_x = x + 136;
  let avatarurl_y = headY + (preOffsetY + barHeight) + 4;
  let r = avatarSize/2;
  context.save();

  context.beginPath();
  context.arc(avatarurl_x+r, avatarurl_y+r, r, Math.PI * 2, false);
  context.clip();
  context_drawImage(assetsAvatarUrl[myOpenId], avatarurl_x, avatarurl_y, avatarSize, avatarSize);
  context.restore();

  //绘制名字
  context.fillStyle = '#024C90';
  context.font = '24px Arial';
  context.fillText(getNameSlice(myNickName + ""), x + 240, tempstartY + 24 + (preOffsetY + barHeight));
  
  //绘制分数
  let score = myCurrentScore;
  if(curDataType == 'score')
    context.fillText('第'+score+'关', x + 388, tempstartY + 24 +  (preOffsetY + barHeight));
  else
    context.fillText(score+'分', x + 388, tempstartY + 24 + (preOffsetY + barHeight));
}

/**
 * 点击处理
 */
function onTouchEnd(event) {
  let x = event.clientX * sharedCanvas.width / canvasWidth;
  let y = event.clientY * sharedCanvas.height / canvasHeight;
  if (x > lastButtonX && x < lastButtonX + buttonWidth &&
    y > lastButtonY && y < lastButtonY + buttonHeight) {
    //在last按钮的范围内
    if (page > 0) {
      buttonClick(0);
    }
  }
  if (x > nextButtonX && x < nextButtonX + buttonWidth &&
    y > nextButtonY && y < nextButtonY + buttonHeight) {
    //在next按钮的范围内
    if ((page + 1) * perPageMaxNum < totalGroup.length) {
      buttonClick(1);
    }
  }

}
/**
 * 根据传入的buttonKey 执行点击处理
 * 0 为上一页按钮
 * 1 为下一页按钮
 */
function buttonClick(buttonKey) {
  let old_buttonY;
  if (buttonKey == 0 && page > 0) {
    //上一页按钮
    page--;
    startIndex -= 5;
    renderDirty = true;
    console.log('上一页' + page);
    setTimeout(() => {
      //重新渲染必须标脏
      renderDirty = true;
    }, 100);
  } else if (buttonKey == 1 && (page + 1) * perPageMaxNum < totalGroup.length) {
    //下一页按钮
    startIndex += 5;
    page++;
    renderDirty = true;
    console.log('下一页' + page);
    setTimeout(() => {
      //重新渲染必须标脏
      renderDirty = true;
    }, 100);
  }

}

/**
 * 即将超越好友显示
 */
function showFriendReadyToBeyond(curScore) {
  console.log("showFriendReadyToBeyond...myRank:" + myRank + " curScore:" + curScore + " len:" + totalGroup.length + " firstScore:" + getScoreByIndex(0) + " myNickName:" + myNickName);
  context.setTransform(1, 0, 0, 1, 0, 0);
  context.clearRect(0, 0, sharedCanvas.width, sharedCanvas.height);
  let firstScore = getScoreByIndex(0);
  //这次分数比排行榜最高分数还要高就不显示即将超越
  if (curScore >= firstScore) {
    return;
  }
  if (totalGroup.length == 0) {
    return;
  }

  let score = 0;
  let nickName = '';
  let avatarUrl = null;
  let beyondIndex = 0;
  if (totalGroup.length == 1) {
    if (totalGroup[0].openid != myOpenId) {
      score = getScoreByIndex(0);
      if (curScore > score) {
        avatarUrl = assetsAvatarUrl[totalGroup[0].openid];
        beyondIndex = 0;
        nickName = totalGroup[0].nickname;
      }
    }
  } else {
    for (var i = totalGroup.length - 1; i >= 0; i--) {
      if (totalGroup[i].openid != myOpenId) {
        score = getScoreByIndex(i);
        nickName = totalGroup[i].nickname;
        if (curScore < score) {
          beyondIndex = i;
          avatarUrl = assetsAvatarUrl[totalGroup[beyondIndex].openid];
          break;
        }
        else if (curScore > getScoreByIndex(i) && curScore < getScoreByIndex(i - 1)) {
          score = getScoreByIndex(i - 1);
          nickName = totalGroup[i-1].nickname;
          beyondIndex = i - 1;
          if (beyondIndex >= 1){
            if (totalGroup[beyondIndex].openid == myOpenId) {
              beyondIndex = beyondIndex - 1;
            }
            avatarUrl = assetsAvatarUrl[totalGroup[beyondIndex].openid];
          }else{
            if (totalGroup[beyondIndex].openid != myOpenId) {
              avatarUrl = assetsAvatarUrl[totalGroup[beyondIndex].openid];
            }
          }
          break;
        }
      }
    }
  }

  if (avatarUrl == null){
    return;
  }

  stageWidth = sharedCanvas.width;
  stageHeight = sharedCanvas.height;

  let fontColor = "white";
  context.font = '22px 黑体';
  context.fillStyle = 'white';
  context.textAlign="center";
  //标题
  context.fillText('即将超越', 50, 22);
  context.font = '20px 黑体';
  //分数
  context.fillText(score, 50, 48);

  drawRoundedRect(12, 56, 76, 76, 12, true)
  //头像
  // context_drawImage(assets.rank_frame, headPosX+20, headSize / 2 + 32, headSize + 12, headSize + 12);
  context_drawImage(avatarUrl, 12, 56, 76, 76);
  context.restore(); 

  context.font = '22px 黑体';
  context.fillText(nickName, 50, 155);

  // // let score = getScoreByIndex(myRank - 2);
  // let scorePosX = headPosX + 155;
  // let scorePosY = headSize / 2 + 65;
  // let rankNumWidth = 30;
  
}

function drawRoundedRect(x, y, width, height, r, clip, fill = false, stroke = false) {
  context.save(); 
  context.beginPath(); // draw top and top right corner 
  context.moveTo(x + r, y);
  context.arcTo(x + width, y, x + width, y + r, r); // draw right side and bottom right corner 
  context.arcTo(x + width, y + height, x + width - r, y + height, r); // draw bottom and bottom left corner 
  context.arcTo(x, y + height, x, y + height - r, r); // draw left and top left corner 
  context.arcTo(x, y, x + r, y, r);
  if (fill) { context.fill(); }
  if (stroke) { context.stroke(); }
  if (clip) {context.clip();}
}

function getScoreByIndex(index) {
  let kvDataList = totalGroup[index].KVDataList;
  let kvData = kvDataList[0];
  let data = JSON.parse(kvData['value'])
  return data['wxgame']['score']
}

/////////////////////////////////////////////////////////////////// 相关缓存数据

///////////////////////////////////数据相关/////////////////////////////////////

/**
 * 渲染标脏量
 * 会在被标脏（true）后重新渲染
 */
let renderDirty = true;

/**
 * 当前绘制组
 */
let currentGroup = [];
/**
 * 每页最多显示个数
 */
let perPageMaxNum = 5;
/**
 * 当前页数,默认0为第一页
 */
let page = 0;
///////////////////////////////////绘制相关///////////////////////////////
/**
 * 舞台大小
 */
let stageWidth;
let stageHeight;
/**
 * 排行榜大小
 */
let rankWidth;
let rankHeight;

/**
 * 每个头像条目的大小
 */
let barWidth;
let barHeight;
/**
 * 条目与排行榜边界的水平距离
 */
let offsetX_barToRank
/**
 * 绘制排行榜起始点X
 */
let startX;
/**
 * 绘制排行榜起始点Y
 */
let startY;
/**
 * 每行Y轴间隔offsetY
 */
let preOffsetY;
/**
 * 按钮大小
 */
let buttonWidth;
let buttonHeight;
/**
 * 上一页按钮X坐标
 */
let lastButtonX;
/**
 * 下一页按钮x坐标
 */
let nextButtonX;
/**
 * 上一页按钮y坐标
 */
let lastButtonY;
/**
 * 下一页按钮y坐标
 */
let nextButtonY;
/**
 * 两个按钮的间距
 */
let buttonOffset;

/**
 * 字体大小
 */
let fontSize;
/**
 * 文本文字Y轴偏移量
 * 可以使文本相对于图片大小居中
 */
let textOffsetY;
/**
 * 头像大小
 */
let avatarSize;
/**
 * 名字文本最大宽度，名称会根据
 */
let textMaxSize;
/**
 * 绘制元素之间的间隔量
 */
let intervalX;
/**
 * 排行榜与舞台边界的水平距离
 */
let offsetX_rankToBorder;
/**
 * 排行榜与舞台边界的竖直距离
 */
let offsetY_rankToBorder;
/**
 * 绘制排名的最大宽度
 */
let indexWidth;

/**
 * 是否加载过资源的标记量
 */
let hasLoadRes;

/**
 * 资源加载
 */
function preloadAssets() {
  let preloaded = 0;
  let count = 0;
  for (let asset in assetsUrl) {
    count++;
    const img = wx.createImage();
    img.onload = () => {
      preloaded++;
      if (preloaded == count) {
        // console.log("加载完成");
        hasLoadRes = true;
      }

    }
    img.src = assetsUrl[asset];
    assets[asset] = img;
  }
}


/**
 * 绘制屏幕
 * 这个函数会在加载完所有资源之后被调用
 */
function createScene() {
  if (sharedCanvas.width && sharedCanvas.height) {
    // console.log('初始化完成')
    stageWidth = sharedCanvas.width;
    stageHeight = sharedCanvas.height;
    init();
    return true;
  } else {
    console.log('创建开放数据域失败，请检查是否加载开放数据域资源');
    return false;
  }
}


//记录requestAnimationFrame的ID
let requestAnimationFrameID;
let hasCreateScene;

/**
 * 增加来自主域的监听函数
 */
function addOpenDataContextListener() {
  wx.onMessage((data) => {
    if (data.command == 'open') {

      // if (!hasCreateScene) {
      //   //创建并初始化
      //   hasCreateScene = createScene(); 
      // }
      // requestAnimationFrameID = requestAnimationFrame(loop);
      GroupType = 1;
      getFriendCloudStorage();
    } else if (data.command == 'close' && requestAnimationFrameID) {
      cancelAnimationFrame(requestAnimationFrameID);
      requestAnimationFrameID = null;
      renderDirty = true;
      page = 0;
      startIndex = 0;
      hasCreateScene = null;
    } else if (data.command == 'loadRes' && !hasLoadRes) {
      /**
       * 加载资源函数
       * 只需要加载一次
       */
      getFriendHeadIcon();
      // getMyUserInfo();
      preloadAssets();
    } else if(data.command == 'nextPage' || data.command == 'lastPage') {
      if(data.command == 'nextPage')
      {
        buttonClick(1);
      }else
      {
        buttonClick(0);
      }
    } else if(data.command == 'setOpenId') {
      myOpenId = data.openId;
    } else if (data.command == 'showFriendReadyToBeyond') {//即将超越的好友
      showFriendReadyToBeyond(data.score);
    } else if(data.command == 'showNearlyFriendRank') {
      GroupType = 2;
      getFriendCloudStorage('score');
    } else {
      GroupType = 1;
      getFriendCloudStorage(data.command);
    }
  });
}

addOpenDataContextListener();

/**
 * 循环函数
 * 每帧判断一下是否需要渲染
 * 如果被标脏，则重新渲染
 */
function loop() {
  if (renderDirty) {
    // console.log(`stageWidth :${stageWidth}   stageHeight:${stageHeight}`)
    context.setTransform(1, 0, 0, 1, 0, 0);
    context.clearRect(0, 0, sharedCanvas.width, sharedCanvas.height);
    drawRankPanel();
    renderDirty = false;
  }
  requestAnimationFrameID = requestAnimationFrame(loop);
}

/**
 * 图片绘制函数
 */
function context_drawImage(image, x, y, width, height) {
  if (image.width != 0 && image.height != 0 && context) {
    if (width && height) {
      context.drawImage(image, x, y, width, height);
    } else {
      context.drawImage(image, x, y);
    }
  }
}